package teacher;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.graphics.PixelFormat;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;

import com.project.institute.DAO.InstituteListDAO;
import com.project.trac.R;

import core.modules.DatabaseConnector;

public class Forum extends InstituteListDAO {
	
	private final int CONTEXT_MENU_DROP = 1;
	private String TITLE = "title";
	private int id = 0;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.generic_list);
		setTitle("Forum Threads for " + getSubjectName());
		
		OnItemClickListener joinGroup = new OnItemClickListener(){

			@Override
			public void onItemClick(AdapterView<?> av, View view, int position, long id) {
				
				String item = av.getItemAtPosition(position).toString().replace("=", "");
				TITLE = item.subSequence(item.indexOf("title") + 5, item.indexOf(", kid")).toString();
				id = Integer.valueOf(item.subSequence(item.indexOf("id") + 2, item.indexOf(", started")).toString());
				
				registerForContextMenu(av);
				openContextMenu(av);
				
			}
			
			
		};


		getListView().setOnItemClickListener(joinGroup);
		
		
		new AsynchronousTask().execute("initialize");
	}
	
	@Override
	public void onAttachedToWindow() {
		super.onAttachedToWindow();
		Window window = getWindow();
		window.setFormat(PixelFormat.RGBA_8888);
	}
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
		menu.setHeaderTitle("Select Action");
		menu.add(Menu.NONE, CONTEXT_MENU_DROP, Menu.NONE, "Drop \"" + TITLE + "\"?");
	}
	
	@SuppressWarnings("deprecation")
	@Override
	public boolean onContextItemSelected(MenuItem item) {

		switch (item.getItemId()) {

		case CONTEXT_MENU_DROP:
			
			AlertDialog ad = new AlertDialog.Builder(Forum.this).create();
			ad.setCancelable(false); // This blocks the 'BACK' button
			ad.setMessage("Really drop " + TITLE + "?");
			ad.setButton("Yes", new DialogInterface.OnClickListener() {
			    @Override
			    public void onClick(DialogInterface dialog, int which) {
			    	new AsynchronousTask().execute("drop");
			        dialog.dismiss();
			        
					startActivity(Forum.this.getIntent());
			    }
			});
			
			ad.setButton2("No", new DialogInterface.OnClickListener() {
			    @Override
			    public void onClick(DialogInterface dialog, int which) {
			        dialog.dismiss();
			    }
			});
			ad.show();
			
			break;
		}
		return super.onContextItemSelected(item);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.menu, menu);
		return true;
	}
	
	@Override
	public void onBackPressed() {
		super.onBackPressed();
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
	        case R.id.menu_logout:
	           Logout(this);
	           return true;
	        default:
	            return super.onOptionsItemSelected(item);
	    }
	}
	
	private class AsynchronousTask extends AsyncTask<String, String, String> {

		HashMap<String, String> m;
		ArrayList<HashMap<String, String>> arrayList = new ArrayList<HashMap<String, String>>();

		ProgressDialog progressDialog;
		ListAdapter listAdapter;
		
		String KEY_TITLE = "title";
		String KEY_DATE_STARTED = "started";
		String KEY_DATE_END = "end";
		String KEY_ID = "kid";
		
		protected void onPreExecute() {
			super.onPreExecute();
			progressDialog = new ProgressDialog(Forum.this);
			progressDialog.setIcon(android.R.drawable.ic_dialog_info);
			progressDialog.setMessage("please wait...");
			progressDialog.setIndeterminate(true);
			progressDialog.setCancelable(true);
			progressDialog.show();

		}

		protected String doInBackground(String... args) {
			try {

				if (args[0].equalsIgnoreCase("initialize")) {
					ResultSet rs = DatabaseConnector.getStatement().executeQuery(
							"SELECT id, title, content, isThread, section, "
							+ " DATE_FORMAT(date_started,'%Y-%b-%d') AS 'started', "
							+ " DATE_FORMAT(date_end,'%Y-%b-%d') AS 'end' "
							+ " FROM forum WHERE uid = " + getUserID() + " AND sid = " + getScheduleID()
							+ " AND replyto_id = 0");

					while (rs.next()) {

						m = new HashMap<String, String>();
						m.put(KEY_TITLE, rs.getString("title"));
						m.put(KEY_DATE_STARTED, rs.getString("started"));
						m.put(KEY_DATE_END, rs.getString("end"));
						m.put(KEY_ID, rs.getString("id"));
						arrayList.add(m);

					}
					
					if (args[0].equalsIgnoreCase("drop")) {
						DatabaseConnector.getConnection().setAutoCommit(false);
						PreparedStatement pps = DatabaseConnector.getConnection().prepareStatement("DELETE FROM forum WHERE id = ? AND replyto_id = ?");
						
						pps.setInt(1, id);	
						pps.setInt(2, id);

						pps.executeUpdate();			
						pps.clearParameters();			
						pps.close();
					}
				}

			} catch (SQLException e) {
				DatabaseConnector.Logger(getClass(), "doInBackground", e);
			} 

			return null;
		}

		protected void onPostExecute(String postExecute) {
			progressDialog.dismiss();
			
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					
					listAdapter = new SimpleAdapter(Forum.this, arrayList,
							R.layout.teacher_forum_detail, 
							new String[] { KEY_TITLE, KEY_DATE_STARTED, KEY_DATE_END, KEY_ID}, 
							new int[] {	R.id.forum_title, R.id.tv_date_started, R.id.tv_date_end});
					setListAdapter(listAdapter);
					
				}

			});

		}

	}

}